// 基础URL
export const baseURL: string = 'https://consult-api.itheima.net/';

interface RenderMetrics {
  totalTime: number;
  chunkCount: number;
  elementsPerSecond: number;
}

// 延迟函数
export const friendlyDelay = (delayMs: number): Promise<void> => {
  return new Promise((resolve) => {
    setTimeout(resolve, delayMs);
  });
};

// 分段渲染函数
export const pageRender = async <T>(
  pageSize: number,
  delayTime: number,
  listData: T[],
  renderFn: (items: T[]) => void
): Promise<RenderMetrics> => {
  return new Promise((resolve) => {
    let listIndex: number = 0;
    let chunkCount: number = 0;

    const startTime = performance.now();

    const hasNextPage = async () => {
      if (listIndex >= listData.length) {
        const endTime: number = performance.now();
        const totalTime: number = endTime - startTime;
        const elementsPerSecond: number = listData.length / (totalTime / 1000);
        resolve({
          totalTime,
          chunkCount,
          elementsPerSecond
        });
        return;
      }
      const endIndex: number = Math.min(listIndex + pageSize, listData.length);

      const chunkPage: T[] = listData.slice(listIndex, endIndex);

      listIndex = endIndex;

      await friendlyDelay(delayTime);

      renderFn(chunkPage);

      chunkCount++;
      requestAnimationFrame(hasNextPage);
    };

    hasNextPage();
  });
};

/**
 * 判断是否safair浏览器
 */
export function isSafari() {
  const ua = navigator.userAgent;
  // 检测 Safari 特有标识
  const safariCheck = /safari\//i.test(ua);
  const chromiumCheck = /chrome|chromium|crios|edg|opr|opera|fxios|firefox/i.test(ua);
  const vendorCheck = navigator.vendor && navigator.vendor.includes('Apple');
  return safariCheck && vendorCheck && !chromiumCheck;
}

export function toCamel(str: string): string {
  const arr = str.split('_');
  console.log('arr=>', arr);
}
